package com.ruoyi.common.utils;

import java.io.File;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;


public class FileUpload{

	private static final String[] IMAGE_TYPE = new String[] { ".bmp", ".jpg", ".jpeg", ".gif", ".png", ".mp4", ".MOV",
			".AVI", ".MKV", ".zip" };

	public String upload(MultipartFile uploadFile)
			throws Exception {

		// 校验图片格式
		boolean isLegal = false;
		for (String type : IMAGE_TYPE) {
			if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
				isLegal = true;
				break;
			}
		}

		// 封装Result对象，并且将文件的byte数组放置到result对象中
		PicUploadResult fileUploadResult = new PicUploadResult();

		// 状态
		fileUploadResult.setError(isLegal ? 0 : 1);

		// 文件新路径
		String filePath = "/"+getFilePath(uploadFile.getOriginalFilename());
		//mac
//		String filePath = "/Users/mac/Downloads/"+getFilePath(uploadFile.getOriginalFilename());

//		if (LOGGER.isDebugEnabled()) {
//			LOGGER.debug("Pic file upload .[{}] to [{}] .", uploadFile.getOriginalFilename(), filePath);
//		}

		// 生成图片的绝对引用地址
		String picUrl = StringUtils.replace(StringUtils.substringAfter(filePath, "/image"),
				"\\", "/");
		fileUploadResult.setUrl("" + picUrl);

		File newFile = new File(filePath);

		// 写文件到磁盘
		uploadFile.transferTo(newFile);

//		response.setContentType(MediaType.TEXT_HTML_VALUE);


		//处理数据
		//fileService.upload(uploadFile.getOriginalFilename(),String.valueOf(uploadFile.getSize()),filePath,userid,approver,0);
//		mapper.writeValueAsString(fileUploadResult);


		return "/image"+fileUploadResult.getUrl();
	}


	private String getFilePath(String sourceFileName) {
		String baseFolder = "/image" + File.separator + "image";
		java.util.Date nowDate = new java.util.Date();
		// yyyy/MM/dd
		String fileFolder = baseFolder + File.separator + new DateTime(nowDate).toString("yyyy") + File.separator
				+ new DateTime(nowDate).toString("MM") + File.separator + new DateTime(nowDate).toString("dd");
		File file = new File(fileFolder);
		if (!file.isDirectory()) {
			// 如果目录不存在，则创建目录
			file.mkdirs();
		}
		// 生成新的文件名
		String fileName = new DateTime(nowDate).toString("yyyyMMddhhmmssSSSS") + RandomUtils.nextInt(100) + "."
				+ StringUtils.substringAfterLast(sourceFileName, ".");
		return fileFolder + File.separator + fileName;
	}
}
